package com.cumulus.MoveCopy;


import java.util.ArrayList;

import com.cumulus.acceleration.AccAng;
import com.cumulus.acceleration.AccelerationManager;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.os.CountDownTimer;

public class CreateOwnActivity extends Activity   {

    private static final String TAG = "CreateOwnActivity";
    private AccelerationManager _accelerationManager;
	private Activity _curActivity;
    private SoundPool _soundPool;
    private ArrayList<Integer> _soundID;
    private int _curSoundNum;
	    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.createown_activity);

        int recorder_index=this.getIntent().getExtras().getInt("recorder_index");
        ArrayList<Integer> players = CreateOwnActivity.this.getIntent().
          		getExtras().getIntegerArrayList("player_arr");
        ((TextView)findViewById(R.id.textView1)).setText("Player "+((recorder_index+1)%(players.size())+1)+", Use Your Imagination...");
        _curActivity = this;
        _soundID = new ArrayList<Integer>();
        _curSoundNum = 0;
        _soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        _soundID.add(_soundPool.load(this, R.raw.sound1, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound2, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound3, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound4, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound5, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound6, 1));

		this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

		setTitle("CreateOwnActivity");

    }
    
    public void playSound() {

		_soundPool.play(_soundID.get(_curSoundNum), 1, 1, 1, 0, 1f);
		if(_curSoundNum == _soundID.size() - 1)
			_curSoundNum = 0;
		else
			_curSoundNum ++;
    }
    
    
    public void onResume() {
    	super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.activity_main, menu);
        return false;
    }
    
    public void onPause() {
    	super.onPause();
    }
    
    public void startCountdownForRecord(View view) {
    	Log.d(TAG, "record countdown timer started");
        (new MyCount(4000, 1000)).start();

    }
    
    public class MyCount extends CountDownTimer{
    	
    	private TextView _countdownTimer;
        protected CreateOwnActivity _createOwnActivity;

    	
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            _countdownTimer = (TextView)findViewById(R.id.countdown_timer);
        }

        @Override
        public void onFinish() {
        	_countdownTimer.setText("Go!");
            _countdownTimer = (TextView)findViewById(R.id.countdown_timer);

        	
        	
        	_accelerationManager = new AccelerationManager((SensorManager)getSystemService(SENSOR_SERVICE), _curActivity);
        	
            final int totaltime = 60000;
            int tick = 100;
            
            new CountDownTimer(totaltime, tick) {
            	
                public void onTick(long millisUntilFinished) {
                	
                	// add data to the array
                	/*long milliseconds = (totaltime - millisUntilFinished) % 1000;
                	String millisecondsWithZeros;
                	if(milliseconds < 10)
                		millisecondsWithZeros = "00" + milliseconds;
                	else if(milliseconds < 100)
                		millisecondsWithZeros = "0" + milliseconds;
                	else
                		millisecondsWithZeros = milliseconds + "";*/
                	
                	
                	long milliSeconds = ((totaltime - millisUntilFinished) % 1000) / 100;
                	long timeSinceStart = (totaltime - millisUntilFinished) / 1000;
                	
                	if (timeSinceStart == 2) {
                        ((Button)findViewById(R.id.go_stop_button)).setText("Stop");
                    	((Button)findViewById(R.id.go_stop_button)).setVisibility(View.VISIBLE);

                	}
                	
                	String timeString = "0:" + timeSinceStart + "." + milliSeconds;
                	if (timeSinceStart < 10)
                		timeString = "0:0" + timeSinceStart + "." + milliSeconds;
                	
                	((TextView)findViewById(R.id.stopwatch)).setText(timeString);
                }

                public void onFinish() {

                }
             }.start();

        }

        @Override
        public void onTick(long millisUntilFinished) {
        	_countdownTimer.setText(((int) (millisUntilFinished/1000)) + "");
        	        	
        	((Button)findViewById(R.id.go_stop_button)).setVisibility(View.INVISIBLE);
        	((Button)findViewById(R.id.go_stop_button)).setOnClickListener(doneRecordingListener);
        }

    }
    
    View.OnClickListener doneRecordingListener = new View.OnClickListener() {
        public void onClick(View view) {
        	
        	ArrayList<AccAng> recordingCoordinates = _accelerationManager.stop();
          	Log.d(TAG, "done recording");
          	Log.d(TAG, "reply activity called");
          	
          	
          	ArrayList<Integer> players = CreateOwnActivity.this.getIntent().
          		getExtras().getIntegerArrayList("player_arr");

    		int current_index = CreateOwnActivity.this.getIntent().getExtras().getInt("current_index");
      		int recorder_index = CreateOwnActivity.this.getIntent().getExtras().getInt("recorder_index");
      		int round = CreateOwnActivity.this.getIntent().getExtras().getInt("num_rounds");
      		Intent intent = new Intent(CreateOwnActivity.this, TransitionActivity.class);
           
          	intent.putExtras(CreateOwnActivity.this.getIntent().getExtras());
          	Log.d(TAG, "arr="+ players.toString() + " i=" + current_index);
          	
          	String stopwatchValue = (String) ((TextView)findViewById(R.id.stopwatch)).getText();
          	String[] stopwatchSplitValues = stopwatchValue.split(":");
          	Log.d(TAG, "time since start thing: " + stopwatchSplitValues[1]);
          	int timeSinceStart =(int)(10* Double.parseDouble(stopwatchSplitValues[1]));
          	
          	intent.putExtra("time", timeSinceStart);

          	intent.putIntegerArrayListExtra("player_arr", players);
          	int c=current_index;
          	if(players.size()==current_index+1){
          		current_index=-1;
          	}          		
          	Log.d(TAG,"d"+c+"af "+current_index);
          	if(current_index+1==players.size()){
          		current_index=-1;
          	}
          	Log.d(TAG,"RECORDED  "+recorder_index);
            intent.putExtra("current_index", (current_index+1)%players.size());
            intent.putExtra("attempted",false);
            intent.putExtra("recorder_index", (recorder_index+1)%players.size());
            intent.putExtra("num_rounds", round+1);
          	intent.putStringArrayListExtra("recordingCoordinates", convertAccAngToString(recordingCoordinates));
          	intent.putExtra("newPlayer",0);
          	Log.d(TAG, "arr="+ players.toString() + " i=" + current_index);

          	Log.d(TAG, "putting recording coordinates");
          	intent.putStringArrayListExtra("recordingCoordinates", convertAccAngToString(recordingCoordinates));
          	Log.d(TAG, "done putting  recording coordinates");

            startActivity(intent);
          }
      };
      
      
      public ArrayList<String> convertAccAngToString(ArrayList<AccAng> accAngList) {
    	  
    	  ArrayList<String> stringAccAngList = new ArrayList<String>();
    	 
    	  for (AccAng accAng: accAngList){
    		  
    		  String data = accAng.xA + "," + accAng.yA + "," + accAng.zA + "," + accAng.xC + "," + accAng.yC + "," + accAng.zC;
    		  stringAccAngList.add(data);
    	  }
    	  
    	  return stringAccAngList;
    	  
      }
 }
